#!/usr/bin/env node
var path = require('path'), fs = require('fs');
var rootdir = process.argv[2];

var replaceContent = {
    '#import "MainViewController.h"':
    '#import "MainViewController.h"\n' +
    '#import "APService.h"\n' +
    '#import "JPushPlugin.h"\n' +
    '#import "MaMobClick.h"\n' +
    '#import "MaHomeView.h"',

    '[self.window makeKeyAndVisible];':
    '[self.window makeKeyAndVisible];\n' +
        '[JPushPlugin setLaunchOptions:launchOptions];\n',

    'CGRect screenBounds = [[UIScreen mainScreen] bounds];':
    'CGRect screenBounds = [[UIScreen mainScreen] bounds];\n' +
    ' self.window = [[UIWindow alloc] initWithFrame:screenBounds];\n' +
    ' NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey];\n' +
    '[MaMobClick setAppVersion:version];\n' +
    ' [MaMobClick startWithAppkey:@"u9mp" corpKey:@"u9test"];',
    '[[NSNotificationCenter defaultCenter] postNotificationName:CDVRemoteNotification object:token];':
        '[[NSNotificationCenter defaultCenter] postNotificationName:CDVRemoteNotification object:token];\n'+
            '[APService registerDeviceToken:deviceToken ];\n',

    'CDVPluginHandleOpenURLNotification object:url]];':
    'CDVPluginHandleOpenURLNotification object:url]];\n ' +
    'if([sourceApplication isEqualToString:@"com.yonyou.enterprisehome"]){\n' +
    '[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boardButtonClick:) name:SUNButtonBoarButtonClickNotification object:nil];\n' +
    ' MaHomeView *board = [MaHomeView defaultButtonBoard];\n' +
    ' if (!board.running)\n' +
    ' {\n dispatch_queue_t mainQueue = dispatch_get_main_queue();\n' +
    ' dispatch_async(mainQueue, ^{[board startRunning];});\n' +
    ' }\n'+
    ' self.userName=url.user;\n' +
    ' self.userPassWord=url.password;\n' +
    ' self.host=url.host;\n' +
    ' self.port=url.port;\n' +
    ' }\n',
    
    '@end': '-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{\n' +
    '    //\n' +
    '    // Required\n' +
    '    [APService handleRemoteNotification:userInfo];\n' +
    '[[NSNotificationCenter defaultCenter] postNotificationName:kJPushPluginReceiveNotification object:userInfo];}\n' +
    ' #pragma mark 点击浮动按钮的响应事件\n' +
    ' - (void)boardButtonClick:(NSNotification *)noti {\n' +
    ' NSNumber *num = [noti object];\n' +
    ' switch ([num intValue]) {\n' +
    ' case 0: {\n' +
    ' NSURL *URL = [NSURL URLWithString:@"portal:"];\n' +
    ' [[UIApplication sharedApplication] openURL:URL]; }\n' +
    ' break; case 1:\n' +
    ' {\n' +
    ' MaHomeView *board = [MaHomeView defaultButtonBoard];\n' +
    ' [board stopRunning];\n' +
    ' }\n' +
    ' break ;\n' +
    ' default:\n' +
    ' break;\n' +
    ' }\n' +
    ' }\n' +
    ' @end'
}

var replaceMainView = {
    '#import "MainViewController.h"':
    '#import "MainViewController.h"\n' +
    '#import "MaMobClick.h"',

    '#pragma mark View lifecycle':
    '#pragma mark View lifecycle\n' +
    '- (void) viewWillDisappear:(BOOL)animated\n' +
    '{\n' +
    '   \n'+
    '   [super viewWillDisappear:YES];\n' +
    '   [MaMobClick endLogPageView:@"U9工作台"];\n' +
    '   \n'+
    '}\n' +
    '- (void) viewDidAppear:(BOOL)animated\n' +
    '{\n' +
    '   \n'+
    '   [super viewDidAppear:YES];\n' +
    '   [MaMobClick  beginLogPageView:@"U9工作台"];\n' +
    '   \n'+
    '}'
}
var replaceDe = {
    '@property (nonatomic, strong) IBOutlet CDVViewController* viewController;':
        '@property (nonatomic, strong) IBOutlet CDVViewController* viewController;\n' +
        '@property (nonatomic, strong) IBOutlet NSString* userName;\n' +
        '@property (nonatomic, strong) IBOutlet NSString* userPassWord;\n' +
        '@property (nonatomic, strong) IBOutlet NSString* host;\n' +
        '@property (nonatomic, strong) IBOutlet NSNumber* port;'
}

var androidMain =
    ' protected void onResume() {\n' +
    ' MaMobclickAgent.onResume(this);\n' +
    ' super.onResume();\n' +
    ' JPushInterface.onResume(this);\n' +
    ' } \n' +
    ' @Override \n' +
    ' protected void onPause() {\n' +
    ' MaMobclickAgent.onPause(this,"U9工作台");\n' +
    ' super.onPause();\n' +
    ' JPushInterface.onPause(this);\n' +
    ' }',
    replaceStr = {
        "import org.apache.cordova.*;":
            "import org.apache.cordova.*;\n" +
            " import cn.jpush.android.api.JPushInterface;\n" +
            " import com.yonyou.ma.platform.modul.analytics.MaMobclickAgent;"
    };
function pipeFile(path) {
    fs.readFile(path, "utf8", function (err, data) {
        if (err) {
            console.log('error');
            return;
        }
        var fileData;
        fileData = replaceFn(data);
        fs.writeFile(path, fileData, 'utf8');

    })
}
function pipeMianFile(path) {
    fs.readFile(path, "utf8", function (err, data) {
        if (err) {
            console.log('error');
            return;
        }
        var mainFileData;
        mainFileData = replaceMain(data);
        fs.writeFile(path, mainFileData, 'utf8');

    })
}

function pipeDeFile(path) {
    fs.readFile(path, "utf8", function (err, data) {
        if (err) {
            console.log('error');
            return;
        }
        var deFileData;
        deFileData = replaceDeData(data);
        fs.writeFile(path, deFileData, 'utf8');

    })
}
function insertMain(path) {
    fs.readFile(path, "utf8", function (err, data) {
        if (err) {
            console.log('error');
            return;
        }
        data = data.replace(Object.keys(replaceStr)[0], replaceStr[Object.keys(replaceStr)[0]]);
        var tmp = data.toString().split('}'), content = "";
        tmp.splice(1, 1, androidMain);
        content = tmp.join('}');
        fs.writeFile(path, content, 'utf8')

    })
}
function replaceFn(data) {
    var arg = Object.keys(replaceContent);
    for (var i = 0; i < arg.length; i++) {
        if (data.indexOf(arg[i]) > -1) {
            data = data.replace(arg[i], replaceContent[arg[i]]);
        }
    }
    return data;
}
function replaceMain(data) {
    var arg = Object.keys(replaceMainView);
    for (var i = 0; i < arg.length; i++) {
        if (data.indexOf(arg[i]) > -1) {
            data = data.replace(arg[i], replaceMainView[arg[i]]);
        }
    }
    return data;
}
function replaceDeData(data) {
    var arg = Object.keys(replaceDe);
    for (var i = 0; i < arg.length; i++) {
        if (data.indexOf(arg[i]) > -1) {
            data = data.replace(arg[i], replaceDe[arg[i]]);
        }
    }
    return data;
}
if (rootdir) {
    var platforms = (process.env.CORDOVA_PLATFORMS ? process.env.CORDOVA_PLATFORMS.split(',') : []);
    for (var x = 0; x < platforms.length; x++) {
        // open up the index.html file at the www root
        try {
            var platform = platforms[x].trim().toLowerCase();
            var indexPath;
            var MainViewPath;
            var appdePath;

            if (platform == 'android') {
                indexPath = path.join('platforms', platform, 'src', 'com', 'yonyouup', 'u9mobile', 'MainActivity.java');
                if (fs.existsSync(indexPath)) {
                    insertMain(indexPath);
                } else {
                    console.log('file error')
                }

            } else {

                indexPath = path.join('platforms', platform, 'U9工作台', 'Classes', 'AppDelegate.m');
                MainViewPath = path.join('platforms', platform, 'U9工作台', 'Classes', 'MainViewController.m');
                appdePath = path.join('platforms', platform, 'U9工作台', 'Classes', 'AppDelegate.h');

                if (fs.existsSync(indexPath)) {
                    pipeFile(indexPath);
                } else {
                    console.log('file error')
                }

                if (fs.existsSync(MainViewPath)) {
                    pipeMianFile(MainViewPath);
                } else {
                    console.log('file error')
                }
                if (fs.existsSync(appdePath)) {
                    pipeDeFile(appdePath);
                } else {
                    console.log('file error')
                }


            }

        } catch (e) {
            process.stdout.write(e);
        }
    }
}



